//
//  TemplateImageEditView.swift
//  TemplateImageEditDemo
//
//  Created by liguandong on 2024/4/12.
//

import Foundation
import UIKit
// 显示操作按钮和边框的界面。
class TemplateEditView4: UIView {
    var onTransformUpate: (() -> Void)?
    // 删除视图的闭包
    var onRemoveViewBlock: (() -> Void)?
    
    lazy var viewContainer: UIView = {
        let v = UIView()
        return v
    }()
    
    private let borderWidth : CGFloat = 4
    private lazy var imageBorder: UIView = {
        let v = UIView(frame: .zero)
        v.layer.borderColor = UIColor.red.cgColor
        v.layer.borderWidth = borderWidth
//        v.layer.shouldRasterize = true
//        v.layer.rasterizationScale = UIScreen.main.scale
        return v
    }()
    
    private lazy var removeCtrl: UIImageView = {
        let v = UIImageView()
        v.isUserInteractionEnabled = true
        v.image = UIImage(named: "AddView_close")
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(removeCtrlTapGesture(_:)))
        v.addGestureRecognizer(tapGesture)
        return v
    }()
    
    private lazy var rotateCtrl: UIImageView = {
        let v = UIImageView()
        v.image = UIImage(named: "AddView_rotate")
        v.isUserInteractionEnabled = true
        v.autoresizingMask = [.flexibleLeftMargin, .flexibleBottomMargin]
        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(rotateCtrlPanGesture(_:)))
        v.addGestureRecognizer(panGesture)
        return v
    }()
    
//    private lazy var rotate90Btn: UIButton = {
//        let v = UIButton()
//        v.setImage(UIImage(named: "AddView_rotate"), for: .normal)
//        v.isUserInteractionEnabled = true
//        v.autoresizingMask = [.flexibleLeftMargin, .flexibleBottomMargin]
//        v.addTarget(self, action: #selector(rotate90), for: .touchUpInside)
//        return v
//    }()
//
    private lazy var rotate90Btn: UIImageView = {
        let v = UIImageView()
        v.image = UIImage(named: "AddView_rotate")
        v.isUserInteractionEnabled = true
        v.autoresizingMask = [.flexibleLeftMargin, .flexibleBottomMargin]
        let tabGesture = UITapGestureRecognizer(target: self, action: #selector(rotate90(_:)))
        v.addGestureRecognizer(tabGesture)
        return v
    }()
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(viewContainer)
        viewContainer.addSubview(imageBorder)
        viewContainer.addSubview(removeCtrl)
        viewContainer.addSubview(rotateCtrl)
        viewContainer.addSubview(rotate90Btn)
        viewContainer.snp.remakeConstraints { make in
            make.edges.equalToSuperview()
        }
        imageBorder.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(Ctrl_Radius)
            make.right.equalToSuperview().offset(-Ctrl_Radius)
            make.top.equalToSuperview().offset(Ctrl_Radius)
            make.bottom.equalToSuperview().offset(-Ctrl_Radius)
        }
        removeCtrl.snp.makeConstraints { make in
            make.width.equalTo(Ctrl_Radius * 2)
            make.height.equalTo(Ctrl_Radius * 2)
            make.centerX.equalTo(imageBorder.snp.left)
            make.centerY.equalTo(imageBorder.snp.top)
        }
        rotateCtrl.snp.makeConstraints { make in
            make.width.equalTo(Ctrl_Radius * 2)
            make.height.equalTo(Ctrl_Radius * 2)
            make.centerX.equalTo(imageBorder.snp.right)
            make.centerY.equalTo(imageBorder.snp.bottom)
        }
        rotate90Btn.snp.makeConstraints { make in
            make.width.equalTo(Ctrl_Radius * 2)
            make.height.equalTo(Ctrl_Radius * 2)
            make.centerX.equalTo(imageBorder.snp.right)
            make.centerY.equalTo(imageBorder.snp.top)
        }
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(onTap(_:)))
        addGestureRecognizer(tapGesture)
    }
    
    @objc private func onTap(_ tapGesture: UITapGestureRecognizer) {
        debugPrint("点框点击，donothing")
    }
    
    
    private var lastRotationCtrlPoint: CGPoint = .zero
    private var lastScaleCtrlPoint: CGPoint = .zero
    @objc private func rotateCtrlPanGesture(_ panGesture: UIPanGestureRecognizer) {
        guard panGesture.state != .began else {
            lastRotationCtrlPoint = convert(rotateCtrl.center, to: superview)
            lastScaleCtrlPoint = lastRotationCtrlPoint
            return
        }

        guard panGesture.state != .ended else { return }
        let ctrlPoint = panGesture.location(in: superview)
        scaleViewWithCtrlPoint(ctrlPoint)
        rotateViewWithCtrlPoint(ctrlPoint)
        onTransformUpate?()
    }
    
    @objc private func rotate90(_ tabGesture: UITapGestureRecognizer){
        transform = transform.rotated(by: 90)
        onTransformUpate?()
    }
    
    @objc private func removeCtrlTapGesture(_ tapGesture: UITapGestureRecognizer) {
        onRemoveViewBlock?()
        snp.removeConstraints()
    }
    
    func resetState(_ imageView : TemplateImageView4){
        snp.remakeConstraints { make in
            make.left.equalTo(imageView.snp.left).offset(-Ctrl_Radius)
            make.right.equalTo(imageView.snp.right).offset(Ctrl_Radius)
            make.top.equalTo(imageView.snp.top).offset(-Ctrl_Radius)
            make.bottom.equalTo(imageView.snp.bottom).offset(Ctrl_Radius)
        }
        transform = imageView.transform
        rotateCtrl.transform = .identity
        removeCtrl.transform = .identity
        rotate90Btn.transform = .identity
        fitCtrlScale(getViewTransformScale())
    }
    
    func rorateView(_ rotationAngle: CGFloat){
        transform = transform.rotated(by: rotationAngle)
        onTransformUpate?()
    }
    
    func translationView(x:CGFloat,y : CGFloat){
        translateDirectly(x: x, y: y)
        onTransformUpate?()
    }
    
    func scaleView(_ scale : CGFloat) -> Bool{
        if getViewTransformScale() <= 0.5 && scale <= 1{
            return false
        }
        scaleByCenter(scale)
        fitCtrlScale(scale)
        return true
    }
    
    // MARK: - Private Methods
    private func fitCtrlScale(_ scale : CGFloat) {
        removeCtrl.scaleByCenter(1 / scale)
        rotateCtrl.scaleByCenter(1 / scale)
        rotate90Btn.scaleByCenter(1 / scale)
        imageBorder.layer.borderWidth = 1 / getViewTransformScale() * borderWidth
    }
    
    
    private func scaleViewWithCtrlPoint(_ ctrlPoint: CGPoint) {
        let transformedCenter = CGPoint(x: frame.midX, y: frame.midY)
        let preDistance = distanceWithStartPoint(transformedCenter, endPoint: lastScaleCtrlPoint)
        let newDistance = distanceWithStartPoint(transformedCenter, endPoint: ctrlPoint)
        let scale = newDistance / preDistance
        if scaleView(scale){
            lastScaleCtrlPoint = ctrlPoint
        }
    }
    private func rotateViewWithCtrlPoint(_ ctrlPoint: CGPoint) {
        let newCenter = ctrlPoint
        let parentCenter = CGPoint(x: frame.midX, y: frame.midY)
        let angle = atan2(parentCenter.y - newCenter.y, newCenter.x - parentCenter.x)
        let lastAngle = atan2(parentCenter.y - lastRotationCtrlPoint.y, lastRotationCtrlPoint.x - parentCenter.x)
        let rotationAngle = -angle + lastAngle
        rotateByCenter(rotationAngle)
        lastRotationCtrlPoint = ctrlPoint
    }
    
    
    private func distanceWithStartPoint(_ start: CGPoint, endPoint end: CGPoint) -> CGFloat {
        let x = start.x - end.x
        let y = start.y - end.y
        return sqrt(x * x + y * y)
    }
 
    

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func getViewTransformScale() -> CGFloat {
        let transform = self.transform
        let scaleX = sqrt(transform.a * transform.a + transform.c * transform.c)
        return scaleX
    }

}

